package net.xuzhen97.distributed.transaction.course.common.util;

import net.xuzhen97.distributed.transaction.course.common.Constant;
import net.xuzhen97.distributed.transaction.course.common.exception.CheckException;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 用户工具类，用来封装当前用户逻辑
 * @author xuzhen
 */
public final class UserUtil {

    /**
     * 获取当前用户id
     * 非request请求使用工具类抛出CheckException
     * currentUserId 获取不到 抛出CheckException
     * @return
     */
    public static String getCurrentUserId(){
        ServletRequestAttributes servletRequestAttributes = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes());
        if (null == servletRequestAttributes) {
            throw new CheckException("request获取error!!!");
        }
        String currentUserId = servletRequestAttributes.getRequest().getHeader(Constant.HEADER_CURRENT_USER_ID);
        if(StringUtils.isEmpty(currentUserId)){
            throw new CheckException("当前用户id获取异常!!!");
        }
        return currentUserId;
    }
}
